﻿using System;
using System.ComponentModel.Composition;
using BizControl.Library.BusinessObjects.Participants;
using Csla.Xaml;
using Microsoft.Practices.Prism.Regions;
using BizControl.Library.BusinessObjects.Activities;
using BizControl.Presentation.Infrastructure.Helpers;
using Microsoft.Practices.Prism;
using BizControl.Presentation.Infrastructure.Constants;
using System.ComponentModel;
using BizControl.Presentation.Infrastructure.Controls;

namespace BizControl.Presentation.ParticipantsModule.ViewModels
{
  [Export]
  public class ParticipantsViewModel : ViewModel<ActivityParticipants>, INavigationAware, IRegionMemberLifetime, IConfirmNavigationRequest, IHeaderInfoProvider<string>
  {
    [Import]
    private IRegionManager _regionManager;

    public ParticipantsViewModel()
    {
      ManageObjectLifetime = false;
      DoRefresh(GetActivityParticipants);
    }

    ActivityParticipants GetActivityParticipants()
    {
      return ViewRegionContext != null ? ((ActivityBO)ViewRegionContext.Value).Participants : null;
    }

    #region Handlers

    public void ViewRegionContextOnPropertyChangedEvent(object sender, PropertyChangedEventArgs args)
    {
      if (args.PropertyName == "Value")
        DoRefresh(GetActivityParticipants);
    }

    #endregion

    #region Properties

    private ObservableObject<object> _viewRegionContext;
    public ObservableObject<object> ViewRegionContext
    {
      get { return _viewRegionContext; }
      set
      {
        HandlersHelper.RemoveHandler(_viewRegionContext, ViewRegionContextOnPropertyChangedEvent);
        _viewRegionContext = value;
        HandlersHelper.AddHandler(_viewRegionContext, ViewRegionContextOnPropertyChangedEvent);
      }
    }

    #endregion

    #region INavigationAware Members

    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
      if (navigationContext.Uri.OriginalString.Contains(ViewNames.ParticipantsViewName))
        return true;
      return false;
    }

    public void OnNavigatedFrom(NavigationContext navigationContext)
    {
      ViewRegionContext = null;
    }

    public void OnNavigatedTo(NavigationContext navigationContext)
    {
    }

    #endregion

    #region IRegionMemberLifetime Members

    public bool KeepAlive
    {
      get { return true; }
    }

    #endregion

    #region IConfirmNavigationRequest Members

    public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
    {
    }

    #endregion

    #region IHeaderInfoProvider<string> Members

    public string HeaderInfo
    {
      get { return BizControl.Presentation.ParticipantsModule.Properties.Resources.ParticipantsHeaderInfo; }
    }

    #endregion
  }

}
